package dk.mirasola.systemtraining.bridgewidgets.client.ui.editor;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import dk.mirasola.systemtraining.bridgewidgets.client.ui.RenderUtil;
import dk.mirasola.systemtraining.bridgewidgets.shared.model.Suit;

import java.util.HashSet;
import java.util.Set;

public class SuitsEditor extends Composite implements LeafValueEditor<Set<Suit>> {
    interface SuitsEditorUIBinder extends UiBinder<Widget, SuitsEditor> {
    }

    private static SuitsEditorUIBinder uiBinder = GWT.create(SuitsEditorUIBinder.class);

    @UiField
    CheckBox spade;
    @UiField
    CheckBox heart;
    @UiField
    CheckBox diamond;
    @UiField
    CheckBox club;

    public SuitsEditor() {
        initWidget(uiBinder.createAndBindUi(this));
        spade.setHTML(renderSuit(Suit.SPADE));
        heart.setHTML(renderSuit(Suit.HEART));
        diamond.setHTML(renderSuit(Suit.DIAMOND));
        club.setHTML(renderSuit(Suit.CLUB));
    }

    private SafeHtml renderSuit(Suit suit) {
        SafeHtmlBuilder sb = new SafeHtmlBuilder();
        sb.appendHtmlConstant("&nbsp;");
        sb.append(RenderUtil.renderSuit(suit));
        return sb.toSafeHtml();
    }

    @Override
    public void setValue(Set<Suit> suits) {
        if (suits == null) {
            throw new NullPointerException();
        }

        spade.setValue(suits.contains(Suit.SPADE));
        heart.setValue(suits.contains(Suit.HEART));
        diamond.setValue(suits.contains(Suit.DIAMOND));
        club.setValue(suits.contains(Suit.CLUB));
    }

    public Set<Suit> getValue() {
        Set<Suit> seats = new HashSet<Suit>();
        if (spade.getValue()) {
            seats.add(Suit.SPADE);
        }
        if (heart.getValue()) {
            seats.add(Suit.HEART);
        }
        if (diamond.getValue()) {
            seats.add(Suit.DIAMOND);
        }
        if (club.getValue()) {
            seats.add(Suit.CLUB);
        }
        return seats;
    }
}
